﻿@inject IBaiduOcr OcrService
@inject ToastService ToastService
@implements IDisposable

<ValidateForm Model="Model" OnValidSubmit="@Verify">
    <EditorForm TModel="InvoiceForm" RowType="RowType.Inline" AutoGenerateAllItem="false">
        <FieldItems>
            <EditorItem @bind-Field="@context.InvoiceType" Text="发票种类" />
            <EditorItem @bind-Field="@context.InvoiceCode" Text="发票代码" />
            <EditorItem @bind-Field="@context.InvoiceNum" Text="发票号码" />
            <EditorItem @bind-Field="@context.InvoiceDate" Text="开票日期" PlaceHolder="YYYYMMDD" />
            <EditorItem @bind-Field="@context.CheckCode" Text="校验码" PlaceHolder="后六位" />
            <EditorItem @bind-Field="@context.TotalAmount" Text="金额" PlaceHolder="可为空" />
        </FieldItems>
        <Buttons>
            <Button ButtonType="ButtonType.Submit" Icon="fa-solid fa-check" Text="Verify" />
        </Buttons>
    </EditorForm>
</ValidateForm>

@code {
    private CancellationTokenSource? TokenSource { get; set; }

    private InvoiceForm Model { get; set; } = new() { InvoiceType = "elec_special_vat_invoice", TotalAmount = "0" };

    private async Task Verify(EditContext context)
    {
        var result = await OcrService.VerifyInvoiceAsync(Model.InvoiceCode, Model.InvoiceNum, Model.InvoiceDate, Model.InvoiceType, Model.CheckCode, Model.TotalAmount);
        if (result.ErrorCode != 0)
        {
            await ToastService.Information("Verify Vat", $"{result.ErrorCode}: {result.ErrorMessage}");
        }
        else if (result.Entity != null)
        {
            await ToastService.Success("Verify Vat", result.Entity?.VerifyMessage);
        }
    }

    /// <summary>
    /// 关闭网页时调用
    /// </summary>
    /// <param name="disposing"></param>
    /// <returns></returns>
    protected virtual void Dispose(bool disposing)
    {
        if (disposing && TokenSource != null)
        {
            TokenSource.Cancel();
            TokenSource.Dispose();
        }
    }

    /// <summary>
    /// 关闭网页时调用
    /// </summary>
    /// <returns></returns>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private class InvoiceForm
    {
        [Required(ErrorMessage = "发票代码不能为空")]
        [NotNull]
        public string? InvoiceCode { get; set; }

        [Required(ErrorMessage = "发票号码不能为空")]
        [NotNull]
        public string? InvoiceNum { get; set; }

        [Required(ErrorMessage = "开票日期不能为空")]
        [NotNull]
        public string? InvoiceDate { get; set; }

        [NotNull]
        public string? InvoiceType { get; set; }

        [Required(ErrorMessage = "校验码不能为空")]
        [NotNull]
        public string? CheckCode { get; set; }

        [NotNull]
        public string? TotalAmount { get; set; }
    }
}
